package xuli.service.impl;

import entity.Product_Info;

import xuli.dao.*;
import xuli.dao.impl.*;
import entity.Warehouse_Product;
import xuli.service.ProductHomeService;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ProductHomeServiceImpl implements ProductHomeService {
    private ProductInfoDao productInfoDao = new ProductInfoDaoImpl();
    private WareHouseProductDao wareHouseProductDao = new WareHouseProductDaoImpl();
    private ProductPicDao productPicDao = new ProductPicDaoImpl();


    @Override
    public Product_Info findProductById(Integer id) {
        Product_Info productInfo = productInfoDao.findProductById(id);
        if (productInfo == null) {
            return null;
        }
        productInfo.setProduct_pic_infos(productPicDao.getProductAllPic(id));
        productInfo.setWarehouse_products(wareHouseProductDao.getProductAllModelType(id));
        return productInfo;
    }


    @Override
    public Warehouse_Product findWarehouseById(String productId, Integer modelId) {
        return wareHouseProductDao.findByIdAndModelId(productId, modelId);
    }

    @Override
    public List<Product_Info> findRandom(Integer nums) {
        List<Product_Info> random = productInfoDao.findRandom(nums);
        List<Product_Info> productInfos = new ArrayList<>();
        for (Product_Info productInfo : random) {
            List<Warehouse_Product> productAllModelType = wareHouseProductDao.getProductAllModelType(productInfo.getProduct_id());
            productInfo.setProduct_Pic_Info(productPicDao.findMasterPic(productInfo.getProduct_id()));
            if(productAllModelType == null || productAllModelType.isEmpty()){
                productInfos.add(productInfo);
            }else{
                for (Warehouse_Product warehouseProduct : productAllModelType) {
                    productInfo.setWarehouseProduct(warehouseProduct);
                    Product_Info o = null;
                    try {
                        ByteArrayOutputStream bo = new ByteArrayOutputStream();
                        ObjectOutputStream oos = new ObjectOutputStream(bo);
                        oos.writeObject(productInfo);
                        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
                        ObjectInputStream ois = new ObjectInputStream(bi);
                        o = (Product_Info)ois.readObject();
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    productInfos.add(o);
                }
            }
        }
        return productInfos;
    }


}
